<template>
	<view class="vehicle-selector">
		<!-- 选择器标题 -->
		<view class="selector-title" v-if="title">
			<text class="title-text">{{ title }}</text>
			<text class="required" v-if="required">*</text>
		</view>

		<!-- 车辆选择显示区域 -->
		<view class="selector-display" @click="showVehicleModal">
			<view class="selected-vehicle" v-if="selectedVehicle">
				<view class="vehicle-info">
					<text class="plate-number">{{ selectedVehicle.plate_number }}</text>
					<view class="vehicle-details">
						<text class="vehicle-type">{{ getVehicleTypeName(selectedVehicle.vehicle_type) }}</text>
						<text class="vehicle-brand" v-if="selectedVehicle.brand || selectedVehicle.model">
							{{ selectedVehicle.brand }} {{ selectedVehicle.model }}
						</text>
					</view>
				</view>
				<view class="default-badge" v-if="selectedVehicle.is_default">
					<text class="badge-text">默认</text>
				</view>
			</view>
			<view class="placeholder" v-else>
				<text class="placeholder-text">{{ placeholder }}</text>
			</view>
			<text class="selector-arrow">></text>
		</view>

		<!-- 错误提示 -->
		<view class="error-message" v-if="errorMessage">
			<text class="error-text">{{ errorMessage }}</text>
		</view>

		<!-- 车辆选择弹窗 -->
		<view class="vehicle-modal" v-if="showModal" @click="closeModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">选择车辆</text>
					<text class="modal-close" @click="closeModal">×</text>
				</view>
				
				<view class="vehicle-list" v-if="vehicles.length > 0">
					<view 
						class="vehicle-item"
						:class="{ selected: vehicle.id === selectedVehicleId }"
						v-for="vehicle in vehicles"
						:key="vehicle.id"
						@click="selectVehicle(vehicle)"
					>
						<view class="vehicle-info">
							<view class="vehicle-plate">
								<text class="plate-number">{{ vehicle.plate_number }}</text>
								<view class="default-badge" v-if="vehicle.is_default">
									<text class="badge-text">默认</text>
								</view>
							</view>
							<view class="vehicle-details">
								<text class="vehicle-type">{{ getVehicleTypeName(vehicle.vehicle_type) }}</text>
								<text class="vehicle-brand" v-if="vehicle.brand || vehicle.model">
									{{ vehicle.brand }} {{ vehicle.model }}
								</text>
								<text class="vehicle-color" v-if="vehicle.color">{{ vehicle.color }}</text>
							</view>
						</view>
						<view class="select-indicator" v-if="vehicle.id === selectedVehicleId">
							<text class="indicator-text">✓</text>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-else>
					<view class="empty-icon">🚗</view>
					<text class="empty-title">还没有车辆信息</text>
					<text class="empty-desc">添加车辆信息后可快速选择</text>
				</view>

				<!-- 快速添加车辆按钮 -->
				<view class="modal-footer">
					<button class="add-vehicle-btn" @click="goToAddVehicle">
						<text class="add-icon">+</text>
						<text class="add-text">添加新车辆</text>
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import vehicleStorage from '../utils/vehicleStorage.js'
import vehicleValidator from '../utils/vehicleValidator.js'

// Props
const props = defineProps({
	// 选中的车辆ID
	modelValue: {
		type: String,
		default: ''
	},
	// 标题
	title: {
		type: String,
		default: '选择车辆'
	},
	// 占位符文本
	placeholder: {
		type: String,
		default: '请选择车辆'
	},
	// 是否必选
	required: {
		type: Boolean,
		default: false
	},
	// 错误信息
	error: {
		type: String,
		default: ''
	},
	// 是否自动选择默认车辆
	autoSelectDefault: {
		type: Boolean,
		default: true
	}
})

// Emits
const emit = defineEmits(['update:modelValue', 'change', 'vehicleSelected'])

// 响应式数据
const vehicles = ref([])
const showModal = ref(false)
const selectedVehicleId = ref(props.modelValue)
const errorMessage = ref(props.error)

// 计算属性
const selectedVehicle = computed(() => {
	return vehicles.value.find(vehicle => vehicle.id === selectedVehicleId.value) || null
})

// 获取车辆类型显示名称
const getVehicleTypeName = (type) => {
	return vehicleValidator.getVehicleTypeName(type)
}

// 加载车辆列表
const loadVehicles = () => {
	try {
		const vehicleList = vehicleStorage.getAllVehicles()
		vehicles.value = vehicleList
		
		// 如果启用自动选择默认车辆且当前没有选中车辆
		if (props.autoSelectDefault && !selectedVehicleId.value && vehicleList.length > 0) {
			const defaultVehicle = vehicleStorage.getDefaultVehicle()
			if (defaultVehicle) {
				selectVehicle(defaultVehicle)
			}
		}
	} catch (error) {
		console.error('加载车辆列表失败:', error)
	}
}

// 显示车辆选择弹窗
const showVehicleModal = () => {
	loadVehicles() // 每次打开时重新加载，确保数据最新
	showModal.value = true
}

// 关闭弹窗
const closeModal = () => {
	showModal.value = false
}

// 选择车辆
const selectVehicle = (vehicle) => {
	selectedVehicleId.value = vehicle.id
	errorMessage.value = '' // 清除错误信息
	
	// 触发事件
	emit('update:modelValue', vehicle.id)
	emit('change', vehicle)
	emit('vehicleSelected', vehicle)
	
	// 关闭弹窗
	closeModal()
	
	console.log('选择车辆:', vehicle)
}

// 跳转到添加车辆页面
const goToAddVehicle = () => {
	closeModal()
	uni.navigateTo({
		url: '/pages/vehicles/form'
	})
}

// 监听外部传入的值变化
watch(() => props.modelValue, (newValue) => {
	selectedVehicleId.value = newValue
})

// 监听错误信息变化
watch(() => props.error, (newError) => {
	errorMessage.value = newError
})

// 组件挂载时加载车辆列表
onMounted(() => {
	loadVehicles()
})

// 暴露方法给父组件
defineExpose({
	loadVehicles,
	clearSelection: () => {
		selectedVehicleId.value = ''
		emit('update:modelValue', '')
		emit('change', null)
	},
	getSelectedVehicle: () => selectedVehicle.value
})
</script>

<style scoped>
.vehicle-selector {
	width: 100%;
}

.selector-title {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.title-text {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
}

.required {
	color: #ff4757;
	margin-left: 4rpx;
}

.selector-display {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 20rpx;
	border: 2rpx solid #ddd;
	border-radius: 8rpx;
	background-color: #fff;
	min-height: 80rpx;
}

.selected-vehicle {
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex: 1;
}

.vehicle-info {
	flex: 1;
}

.plate-number {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 8rpx;
}

.vehicle-details {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.vehicle-type {
	font-size: 26rpx;
	color: #666;
}

.vehicle-brand {
	font-size: 24rpx;
	color: #888;
}

.default-badge {
	background-color: #ff6b35;
	border-radius: 20rpx;
	padding: 4rpx 12rpx;
	margin-left: 16rpx;
}

.badge-text {
	font-size: 20rpx;
	color: #fff;
}

.placeholder {
	flex: 1;
}

.placeholder-text {
	font-size: 30rpx;
	color: #999;
}

.selector-arrow {
	font-size: 24rpx;
	color: #999;
	transform: rotate(90deg);
	margin-left: 16rpx;
}

.error-message {
	margin-top: 12rpx;
}

.error-text {
	font-size: 24rpx;
	color: #ff4757;
}

.vehicle-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.modal-content {
	background-color: #fff;
	border-radius: 16rpx;
	width: 90%;
	max-width: 700rpx;
	max-height: 80vh;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #eee;
}

.modal-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.modal-close {
	font-size: 48rpx;
	color: #999;
	line-height: 1;
}

.vehicle-list {
	flex: 1;
	overflow-y: auto;
	max-height: 60vh;
}

.vehicle-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.vehicle-item:last-child {
	border-bottom: none;
}

.vehicle-item.selected {
	background-color: #f0f8ff;
}

.vehicle-item:active {
	background-color: #f8f8f8;
}

.vehicle-plate {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
}

.vehicle-color {
	font-size: 24rpx;
	color: #888;
}

.select-indicator {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 48rpx;
	height: 48rpx;
	background-color: #007aff;
	border-radius: 50%;
	margin-left: 20rpx;
}

.indicator-text {
	font-size: 24rpx;
	color: #fff;
	font-weight: bold;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx 40rpx;
	text-align: center;
}

.empty-icon {
	font-size: 80rpx;
	margin-bottom: 30rpx;
	opacity: 0.6;
}

.empty-title {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 12rpx;
}

.empty-desc {
	font-size: 24rpx;
	color: #666;
	line-height: 1.4;
}

.modal-footer {
	padding: 30rpx 40rpx;
	border-top: 1rpx solid #eee;
}

.add-vehicle-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	padding: 24rpx;
	background-color: #007aff;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	font-size: 28rpx;
}

.add-icon {
	font-size: 32rpx;
	margin-right: 8rpx;
}

.add-text {
	font-size: 28rpx;
}
</style>